<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.keyword" placeholder="标题/负责人/职能" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新建
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="编码" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.sn }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="主管" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.superior.fullname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="人员" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.employee_num }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status">
            {{ row.status.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button v-if="row.status.value === 5" size="mini" type="success" @click="handleModifyStatus(row,6)">
            启用
          </el-button>
          <el-button v-if="row.status.value === 6" size="mini" @click="handleModifyStatus(row,5)">
            禁用
          </el-button>
          <el-button v-if="row.status.value === 1 || row.status.value === 5" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
          <el-button size="mini" type="danger" @click="handleShow(row,$index)">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.start" :limit.sync="listQuery.perpage" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="140px" style="width: 400x; margin-left:50px;">
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="主管">
          <el-select v-model="temp.superior_employee_identity" placeholder="主管">
            <el-option v-for="item in employeeOptions" :key="item.identity" :label="item.title" :value="item.identity" />
          </el-select>
        </el-form-item>
        <el-form-item label="职能">
          <el-input v-model="temp.responsibility" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
        <el-form-item label="职责">
          <el-input v-model="temp.obligation" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
        <el-button v-if="temp.status.value === 5" type="success" @click="dialogStatus==='create'?createData(5):updateData(5)">
          保存并启用
        </el-button>
        <el-button v-if="temp.status.value === 6" type="success" @click="dialogStatus==='create'?createData(6):updateData(6)">
          保存并禁用
        </el-button>
        <el-button type="default" @click="dialogStatus==='create'?createData(1):updateData(1)">
          保存并新建
        </el-button>
        <el-button v-if="temp.identity > 0" type="danger" @click="handleDelete(row)">
          删除
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, removeDepartmentById, saveDepartment, changeDepartmentStatusById } from '@/api/authority/department'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        start: 1,
        perpage: 10,
        keyword: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      employeeOptions: [],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        identity: undefined,
        departmentId: 0,
        department_identity: 0,
        superior_employee_identity: undefined,
        obligation: '',
        responsibility: '',
        title: '',
        remark: '',
        status: {
          'label': '',
          'value': 6
        }
      },
      dialogFormVisible: false,
      dialogConfirmFormVisible: false,
      dialogStatus: '',
      textMap: {
        create: '新建组',
        confirm: '组编辑'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        content: [{ required: true, message: 'type is required', trigger: 'change' }],
        remark: [{ required: true, message: 'type is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.start = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      changeDepartmentStatusById({ 'departmentId': row.identity }).then(response => {
        console.log(response)
        if (response.status === 200) {
          this.$notify({
            title: 'Success',
            message: 'Delete Successfully',
            type: 'success',
            duration: 2000
          })
          this.listQuery.start = 1
          this.getList()
        } else {
          this.$notify({
            title: '操作失败',
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        identity: undefined,
        departmentId: 0,
        department_identity: 0,
        superior_employee_identity: undefined,
        obligation: '',
        responsibility: '',
        title: '',
        remark: '',
        status: {
          'label': '',
          'value': 6
        }
      }
    },
    handleShow() {

    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData(actionMode = 0) {
      actionMode = parseInt(actionMode)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveDepartment(this.temp).then(() => {
            this.list.unshift(this.temp)
            if (!actionMode) {
              this.dialogFormVisible = false
            }
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.listQuery.start = 1
            this.getList()
          })
        }
      })
    },
    updateData(actionMode = 0) {
      actionMode = parseInt(actionMode)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.status = tempData.status.value
          tempData.department_identity = tempData.identity
          saveDepartment(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            if (!actionMode) {
              this.dialogFormVisible = false
            }
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            this.listQuery.start = 1
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('您确定删除吗？').then(_ => {
        removeDepartmentById({ 'departmentId': row.identity }).then(response => {
          console.log(response)
          if (response.status === 200) {
            this.$notify({
              title: 'Success',
              message: 'Delete Successfully',
              type: 'success',
              duration: 2000
            })
            this.listQuery.start = 1
            this.getList()
          } else {
            this.$notify({
              title: '操作失败',
              message: response.msg,
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(_ => {

      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
